package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.server.api.PeachApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.pojo.PageInfo;
import com.tanhua.dubbo.server.pojo.PeachSound;
import com.tanhua.server.controller.HuanXinController;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.PeachSoundVo;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: Administrator
 * @date: Created in 2021/3/4 18:36
 * @version: 0.0.1
 * @modified By:
 */
@Service
public class PeachService {

    @Reference(version = "1.0.0")
    private PeachApi peachApi;

    @Autowired
    private RedisTemplate<String,String>redisTemplate;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;
    /**
     * @description 发送语音
     * @author
     * @date
     * @param
     *@return
     */
    public Boolean savePeach(MultipartFile soundFile) {
        //获取登录用户信息
        User user= UserThreadLocal.get();
        try {
            //通过fastdfs获取语音文件路径名
            StorePath storePath = this.storageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(),
                    StringUtils.substringAfter(soundFile.getOriginalFilename(), "."), null);
            String soundUrl = this.fdfsWebServer.getWebServerUrl() + "/" + storePath.getFullPath();
            //查询redis中发送语音次数
            String redisKey="PEACH_SOUND_"+user.getId()+"_"+new DateTime().toString("yyyy-MM-dd");
            String count = this.redisTemplate.opsForValue().get(redisKey);
            if(null==count){
                //如果次数为null说明今天还没有发送语音，可以发送，count赋值为“0”
                count="0";
                PeachSound sound=new PeachSound();
                sound.setUserId(user.getId());
                sound.setSoundUrl(soundUrl);
                sound.setRemainingTimes(9-Long.valueOf(count));
                this.peachApi.savePeachSound(sound);
                //把次数保存到redis，设置24小时有效期
                this.redisTemplate.opsForValue().set(redisKey,count,24*60*60, TimeUnit.SECONDS);
                return true;
                //如果count的值大于等于0或小于10，可以发送
            }else if(Long.valueOf(count)>=0&&Long.valueOf(count)<10){
                //count的值加1
                count=(Long.valueOf(count)+1)+"";
                PeachSound sound=new PeachSound();
                sound.setUserId(user.getId());
                sound.setSoundUrl(soundUrl);
                sound.setRemainingTimes(9-Long.valueOf(count));
                this.peachApi.savePeachSound(sound);
                //把次数保存到redis，设置24小时有效期
                this.redisTemplate.opsForValue().set(redisKey,count,24*60*60, TimeUnit.SECONDS);
                return true;
            }else{
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * @description 接收语音
     * @author
     * @date
     * @param
     *@return
     */
    public PeachSoundVo receiveSound() {
        try {
            //获取登录用户信息
            User user=UserThreadLocal.get();
            //从redis中获取接收语音次数
            String redisKey="QUERY_PEACH_SOUND_"+user.getId()+"_"+new DateTime().toString("yyyy-MM-dd");
            String count = this.redisTemplate.opsForValue().get(redisKey);
            //新建返回前端的PeachSoundVo对象
            PeachSoundVo peachSoundVo=new PeachSoundVo();
            //查询语音列表
            PageInfo<PeachSound> pageInfo = this.peachApi.queryPeachSoundList(1, 50);
            List<PeachSound> records = pageInfo.getRecords();
            //新建一个集合用于存储不含自己发送语音的数据
            List<PeachSound>newList=new ArrayList<>();
            for (PeachSound record : records) {
                //把自己的语音数据排除
                if(record.getUserId().longValue()!=user.getId().longValue()){
                    newList.add(record);
                }
            }
            //随机获取一个语音数据
            PeachSound peachSound = newList.get(RandomUtils.nextInt(0, newList.size() - 1));
            //给peachSoundVo赋值
            peachSoundVo.setSoundUrl(peachSound.getSoundUrl());
            UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(peachSound.getUserId());
            peachSoundVo.setAge(userInfo.getAge());
            peachSoundVo.setAvatar(userInfo.getLogo());
            peachSoundVo.setGender(userInfo.getSex().name().toLowerCase());
            peachSoundVo.setId(userInfo.getUserId());
            peachSoundVo.setNickname(userInfo.getNickName());

            if(null==count){
                //如果count值为null，说明今天还没有接受语音，赋值为0
                count="0";
                //设置可以接收语音次数
                peachSoundVo.setRemainingTimes(Integer.valueOf(9 - Long.valueOf(count)+""));
                //保存redis
                this.redisTemplate.opsForValue().set(redisKey,count,24*60*60,TimeUnit.SECONDS);
                //如果点击喜欢可以喜欢该用户
                if(peachSound.getIsLiked()){
                    this.userLikeApi.saveUserLike(user.getId(),userInfo.getUserId());
                }
                return peachSoundVo;
                //如果count值大于等于0或小于10，可以接收语音
            }else if(Long.valueOf(count)>=0&&Long.valueOf(count)<10){
                //count加1
                count=(Long.valueOf(count)+1)+"";
                //设置剩余次数
                peachSoundVo.setRemainingTimes(Integer.valueOf(9 - Long.valueOf(count)+""));
                //保存redis
                this.redisTemplate.opsForValue().set(redisKey,count,24*60*60,TimeUnit.SECONDS);
                //如果喜欢，可以喜欢该用户
                if(peachSound.getIsLiked()){
                    this.userLikeApi.saveUserLike(user.getId(),userInfo.getUserId());
                }
                return peachSoundVo;
            }else {
                return null;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
       return null;
    }
}
